package com.example.manager.aspect;


import com.example.common.annotation.Log;
import com.example.manager.service.SysOperLogService;
import com.example.manager.utils.LogUtils;
import com.example.model.entity.system.SysOperLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect   //标识是个切面类
@Component
public class LogAspect {

    @Autowired
    private SysOperLogService sysOperLogService;

    //环绕通知
    @Around(value = "@annotation(sysLog)")   //当方法上加上@Log注解时，执行此方法
    public Object doAroundAdvice(ProceedingJoinPoint joinPoint , Log sysLog) {

        SysOperLog sysOperLog = new SysOperLog();

        LogUtils.beforeHandleLog(sysLog, joinPoint, sysOperLog);

        Object result = null;
        try {
            //调用业务方法
            result = joinPoint.proceed();
            LogUtils.afterHandlLog(sysLog, result, sysOperLog, 0, null);
            System.out.println("在业务方法之后执行");
        }catch (Throwable e){
            //业务方法发生异常
            e.printStackTrace();
            LogUtils.afterHandlLog(sysLog, result, sysOperLog, 1, e.getMessage());
            throw  new RuntimeException(e);
        }

        //保存日志数据
        sysOperLogService.save(sysOperLog);

        return result;
    }

}
